package com.xmy.cultivate.service.impl;

import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.request.BookGrantInfoRs;
import com.xmy.cultivate.entity.request.BookGrantRs;
import com.xmy.cultivate.mapper.BookStudentMapper;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 订购学生 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2025-01-04
 */
@Service
public class BookStudentServiceImpl extends ServiceImpl<BookStudentMapper, BookStudent> implements IBookStudentService {

    @Autowired
    BookStudentMapper bookStudentMapper;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IBookGrantInfoService iBookGrantInfoService;

    @Autowired
    ICourseTypeService iCourseTypeService;

    @Autowired
    ISystemErrorLogService iSystemErrorLogService;

    @Autowired
    IBookTextService iBookTextService;


    @Override
    @Transactional
    public Result grantBookForStudent(BookStudent bookStudentParam, String ossImageUrl) {
        Result rs = new Result();
        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
        Map<String, Object> mapResult = new HashMap<>();
        mapResult.put("studentName", bookStudentParam.getStudentName());
        mapResult.put("studentId", bookStudentParam.getStudentId());
        RecordCourse recordCourse = studentGradeMapper.getLastReadingGrade(bookStudentParam.getYearPart(), bookStudentParam.getQuarterNum(), bookStudentParam.getSchoolId(), bookStudentParam.getSubjectsId(), bookStudentParam.getStudentId());
        if (Objects.isNull(recordCourse)) {
            mapResult.put("imageUrl", ossImageUrl);
            mapResult.put("signCode", "10006");
            rs.setData(mapResult);
            rs.setCode(Code.OK);
            rs.setMessage(bookStudentParam.getStudentName() + ":不存在在读信息，发放失败");
            return rs;
        }

/*        bookStudentParam.setSchoolId(recordCourse.getSchoolId());
        bookStudentParam.setClassTypeId(recordCourse.getCourseTypeId());
        bookStudentParam.setYearClassId(recordCourse.getYearClassId());
        bookStudentParam.setSubjectsId(recordCourse.getSubjectsId());

        BookStudent bookStudentPurchase = bookStudentMapper.getBookOneForStudentId(bookStudentParam.getYearPart(), bookStudentParam.getQuarterNum(), bookStudentParam.getSchoolId(), bookStudentParam.getSubjectsId(), bookStudentParam.getStudentId(), bookStudentParam.getYearClassId(), bookStudentParam.getClassTypeId(), bookStudentParam.getLessonType());
        if (!Objects.isNull(bookStudentPurchase)) {
            //1订购中，2已下单，3校区已领取，4发放到教师，5发放到学生
            if (bookStudentPurchase.getStatus().equals(1)) {
                mapResult.put("imageUrl", ossImageUrl);
                mapResult.put("signCode", "10003");
                rs.setData(mapResult);
                rs.setCode(Code.OK);
                rs.setMessage("订购中");
                return rs;
            } else if (bookStudentPurchase.getStatus().equals(2)) {
                mapResult.put("imageUrl", ossImageUrl);
                mapResult.put("signCode", "10003");
                rs.setData(mapResult);
                rs.setCode(Code.OK);
                rs.setMessage("待校区领取，校区领取后才能发放");
                return rs;
            } else if (bookStudentPurchase.getStatus().equals(3)) {
                mapResult.put("imageUrl", ossImageUrl);
                mapResult.put("signCode", "10003");
                rs.setData(mapResult);
                rs.setCode(Code.OK);
                rs.setMessage("待老师领取，老师领取后才能发放");
                return rs;
            } else if (bookStudentPurchase.getStatus().equals(4)) {
                //领取
                bookStudentPurchase.setStatus(5);//发放成功
//                this.updateById(bookStudentPurchase);
                BookGrantInfo bookGrantInfo = new BookGrantInfo();
                bookGrantInfo.setBookStudentId(bookStudentPurchase.getId());
                bookGrantInfo.setGrantId(bookStudentParam.getStudentId());
                bookGrantInfo.setStatus(5);
                bookGrantInfo.setHeadImg(ossImageUrl);
                bookGrantInfo.setYearPart(bookStudentPurchase.getYearPart());
                bookGrantInfo.setQuarterNum(bookStudentPurchase.getQuarterNum());*/
//                iBookGrantInfoService.save(bookGrantInfo);

        String classTypeName = iCourseTypeService.getNameForId(recordCourse.getCourseTypeId());
        mapResult.put("subjectsName", recordCourse.getSubjectsName());
        mapResult.put("classTypeName", classTypeName);
        mapResult.put("teacherName", recordCourse.getTeacherName());
        mapResult.put("gradeName", recordCourse.getGradeName());
        mapResult.put("imageUrl", ossImageUrl);
        mapResult.put("grantDateTime", dateTimeNow);
        mapResult.put("signCode", "10001");
        rs.setData(mapResult);
        rs.setCode(Code.OK);
        rs.setMessage("发放成功");
        return rs;
           /* } else if (bookStudentPurchase.getStatus().equals(5)) {
                QueryWrapper<BookGrantInfo> bookGrantInfoQueryWrapper = new QueryWrapper<>();
                bookGrantInfoQueryWrapper.eq("book_student_id", bookStudentPurchase.getId());
                bookGrantInfoQueryWrapper.eq("status", 5);
                bookGrantInfoQueryWrapper.last("limit 1");
                BookGrantInfo bookGrantInfo = iBookGrantInfoService.getOne(bookGrantInfoQueryWrapper);
                LocalDateTime grantDateTime = null;
                if (!Objects.isNull(bookGrantInfo)) {
                    grantDateTime = bookGrantInfo.getCreatedAt();
                }
                String classTypeName = iCourseTypeService.getNameForId(recordCourse.getCourseTypeId());
                mapResult.put("subjectsName", recordCourse.getSubjectsName());
                mapResult.put("classTypeName", classTypeName);
                mapResult.put("teacherName", recordCourse.getTeacherName());
                mapResult.put("gradeName", recordCourse.getGradeName());
                mapResult.put("imageUrl", ossImageUrl);
                mapResult.put("signCode", "10002");
                mapResult.put("grantDateTime", grantDateTime);
                rs.setData(mapResult);
                rs.setCode(Code.OK);
                rs.setMessage("已经发放");
                return rs;
            }
        } else {
            //不分校区
            bookStudentPurchase = bookStudentMapper.getBookOneForStudentId(bookStudentParam.getYearPart(), bookStudentParam.getQuarterNum(), null, bookStudentParam.getSubjectsId(), bookStudentParam.getStudentId(), bookStudentParam.getYearClassId(), bookStudentParam.getClassTypeId(), bookStudentParam.getLessonType());
            if (!Objects.isNull(bookStudentPurchase)) {
                Organization schollInfo = iOrganizationService.getById(bookStudentPurchase.getId());

                //1订购中，2已下单，3校区已领取，4发放到教师，5发放到学生
                if (bookStudentPurchase.getStatus().equals(1)) {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10003");
                    rs.setData(mapResult);
                    rs.setCode(Code.OK);
                    rs.setMessage("已在" + schollInfo.getName() + "订购中");
                    return rs;
                } else if (bookStudentPurchase.getStatus().equals(2)) {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10003");
                    rs.setData(mapResult);
                    rs.setCode(Code.OK);
                    rs.setMessage("待" + schollInfo.getName() + "校区领取，校区领取后在" + schollInfo.getName() + "校区发放");
                    return rs;
                } else if (bookStudentPurchase.getStatus().equals(3)) {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10003");
                    rs.setData(mapResult);
                    rs.setCode(Code.OK);
                    rs.setMessage("待老师" + schollInfo.getName() + "校区领取，老师领取后在" + schollInfo.getName() + "校区发放");
                    return rs;
                } else if (bookStudentPurchase.getStatus().equals(4)) {
                    //领取
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10004");
                    rs.setData(mapResult);
                    rs.setCode(Code.OK);
                    rs.setMessage("订购的教材在" + schollInfo.getName() + "校区，不能在当前校区领取");
                    return rs;
                } else if (bookStudentPurchase.getStatus().equals(5)) {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10002");
                    rs.setData(mapResult);
                    rs.setCode(Code.OK);
                    rs.setMessage("已经发放");
                    return rs;
                }
            } else {
                //班型，年级
                bookStudentPurchase = bookStudentMapper.getBookOneForStudentId(bookStudentParam.getYearPart(), bookStudentParam.getQuarterNum(), bookStudentParam.getSchoolId(), bookStudentParam.getSubjectsId(), bookStudentParam.getStudentId(), null, null, bookStudentParam.getLessonType());
                if (!Objects.isNull(bookStudentPurchase)) {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10005");
                    rs.setData(mapResult);
                    rs.setCode(Code.OK);
                    rs.setMessage("订购的教材班型不符，重新订购中");
                    return rs;
                } else {
                    //不分校区，班型，年级
                    bookStudentPurchase = bookStudentMapper.getBookOneForStudentId(bookStudentParam.getYearPart(), bookStudentParam.getQuarterNum(), bookStudentParam.getSchoolId(), bookStudentParam.getSubjectsId(), bookStudentParam.getStudentId(), null, null, bookStudentParam.getLessonType());
                    if (!Objects.isNull(bookStudentPurchase)) {
                        mapResult.put("imageUrl", ossImageUrl);
                        mapResult.put("signCode", "10005");
                        rs.setData(mapResult);
                        rs.setCode(Code.OK);
                        rs.setMessage("订购的教材班型不符，重新订购中");
                        return rs;
                    } else {
                        mapResult.put("imageUrl", ossImageUrl);
                        mapResult.put("signCode", "10006");
                        rs.setData(mapResult);
                        rs.setCode(Code.OK);
                        rs.setMessage("教材待订购中");
                        return rs;
                    }
                }
            }
        }
        mapResult.put("imageUrl", ossImageUrl);
        mapResult.put("signCode", "10002");
        rs.setData(mapResult);
        rs.setCode(Code.OK);
        rs.setMessage("教材订购中……");*/
//        return rs;
    }


    @Override
    public Long getNeedGrantCount(Integer yearPart,
                                  Integer quarterNum,
                                  Long schoolId,
                                  Long subjectsId,
                                  Long teacherId,
                                  Integer status) {
        return bookStudentMapper.getNeedGrantCount(yearPart, quarterNum, schoolId, subjectsId, teacherId, status);
    }

    /**
     * 按老师发放
     *
     * @param yearPart
     * @param quarterNum
     * @param ossImageUrl
     * @param adminId
     * @param bookGrantRs
     * @return
     */
    @Override
    @Transactional
    public boolean bookGrant(Integer yearPart,
                             Integer quarterNum,
                             String ossImageUrl,
                             Long adminId,
                             BookGrantRs bookGrantRs
    ) {
        try {
            Integer status = 3;
            Integer laterStatus = 4;
//            if (grantType.equals(5)) {
//                status = 4;
//                laterStatus = 5;
//            }
            LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);

            //学生用书
            List<BookGrantInfoRs> bookGrantInfoRsListForStudent = new ArrayList<>();
            //教师用书
            List<BookGrantInfoRs> bookGrantInfoRsListForTeacher = new ArrayList<>();

            for (BookGrantInfoRs bookGrantInfoRs : bookGrantRs.getBookGrantInfoRsList()) {
                if (bookGrantInfoRs.getBookTextType().equals(1)) {
                    bookGrantInfoRsListForStudent.add(bookGrantInfoRs);
                } else {
                    bookGrantInfoRsListForTeacher.add(bookGrantInfoRs);
                }
            }
            //发放学生用书
            if (bookGrantInfoRsListForStudent.size() > 0) {
                //先添加再记录表，再更新book_student表
                bookStudentMapper.addDataBookGrant(yearPart, quarterNum, adminId, dateTimeNow.toString(), status, laterStatus, ossImageUrl, bookGrantRs, bookGrantInfoRsListForStudent);
                bookStudentMapper.grantBook(yearPart, quarterNum, adminId, status, laterStatus, bookGrantRs, bookGrantInfoRsListForStudent);
            }
            //发放教师用书
            if (bookGrantInfoRsListForTeacher.size() > 0) {
                //先添加再记录表，再更新book_student表
                bookStudentMapper.addDataBookGrantForTeacher(yearPart, quarterNum, adminId, dateTimeNow.toString(), status, laterStatus, ossImageUrl, bookGrantRs, bookGrantInfoRsListForTeacher);
                bookStudentMapper.grantBookForTeacher(yearPart, quarterNum, adminId, status, laterStatus, bookGrantRs, bookGrantInfoRsListForTeacher);
            }


        } catch (Exception e) {
            SystemErrorLog systemErrorLog = new SystemErrorLog();
            systemErrorLog.setContent(e.getMessage());
            systemErrorLog.setType(1);
            systemErrorLog.setRemark("教师教材发放");
            iSystemErrorLogService.save(systemErrorLog);
            return false;
        }
        return true;
    }

    /**
     * 按学生发放
     *
     * @param yearPart
     * @param quarterNum
     * @param ossImageUrl
     * @param adminId
     * @param bookGrantRs
     * @return
     */
    @Override
    @Transactional
    public boolean bookGrantStudent(Integer yearPart,
                                    Integer quarterNum,
                                    String ossImageUrl,
                                    Long adminId,
                                    BookGrantRs bookGrantRs
    ) {
        try {
            Integer status = 4;
            Integer laterStatus = 5;

            LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
            //先添加再记录表，再更新book_student表
            bookStudentMapper.addDataBookGrantStudent(yearPart, quarterNum, adminId, dateTimeNow.toString(), status, laterStatus, ossImageUrl, bookGrantRs);
            bookStudentMapper.grantBookStudent(yearPart, quarterNum, adminId, status, laterStatus, bookGrantRs);
        } catch (Exception e) {
            SystemErrorLog systemErrorLog = new SystemErrorLog();
            systemErrorLog.setContent(e.getMessage());
            systemErrorLog.setType(1);
            systemErrorLog.setRemark("学生教材发放");
            iSystemErrorLogService.save(systemErrorLog);
            return false;
        }
        return true;
    }

    @Override
    public Long getNeedGrantPaperCount(Integer yearPart,
                                       Integer quarterNum,
                                       Long schoolId,
                                       Long subjectsId,
                                       Long teacherId,
                                       Integer status) {
        return bookStudentMapper.getNeedGrantPaperCount(yearPart, quarterNum, schoolId, subjectsId, teacherId, status);
    }

    /**
     * 发放给教师或者学生
     *
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param subjectsId
     * @param teacherId
     * @param grantType  4教师发放，5学生发放
     * @return
     */
    @Override
    @Transactional
    public boolean bookGrantPaper(Integer yearPart,
                                  Integer quarterNum,
                                  Long schoolId,
                                  Long subjectsId,
                                  Long teacherId,
                                  Integer grantType,
                                  String imgOss,
                                  Long adminId) {
        try {
            Integer status = 3;
            Integer laterStatus = 4;
            if (grantType.equals(5)) {
                status = 4;
                laterStatus = 5;
            }
            LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
            //先添加再记录表，再更新book_student表
            bookStudentMapper.addDataBookGrantPaper(yearPart, quarterNum, schoolId, subjectsId, teacherId, dateTimeNow.toString(), status, laterStatus, imgOss, adminId);
            bookStudentMapper.grantBookPaper(yearPart, quarterNum, schoolId, subjectsId, teacherId, status, laterStatus);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 教师可发放
     *
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param subjectsId
     * @param teacherId
     * @param status
     * @param type
     * @return
     */
    @Override
    public List<BookStudent> getDistributable(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Long teacherId, Integer status, Integer type, String bookTextType, Integer isDetails, String studentName, String gradeId, String bookTextId, Long classTypeId, String yearClassId, Integer lessonNum) {
        return bookStudentMapper.getDistributable(yearPart, quarterNum, schoolId, subjectsId, teacherId, status, type, bookTextType, isDetails, studentName, gradeId, bookTextId, classTypeId, yearClassId, lessonNum);
    }

    /**
     * 学生可发放
     *
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param subjectsId
     * @param studentId
     * @param status
     * @return
     */
    @Override
    public List<BookStudent> getDistributableStudent(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Long studentId, Integer status, Integer bookTextType) {
        return bookStudentMapper.getDistributableStudent(yearPart, quarterNum, schoolId, subjectsId, studentId, status, bookTextType);
    }
}
